import 'dart:math';
import 'dart:ui' as ui;

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';

import '../../../../../r.dart';
import '../dd_utils/data.dart';
import '../dd_utils/recorder.dart';
import 'wave.dart';

part 'recording_status_mask.dart';
part 'canvas.dart';

class SoundsMessageButton extends StatefulWidget {
  const SoundsMessageButton({
    super.key,
    this.maskData = const RecordingMaskOverlayData(),
    this.builder,
    this.onChanged,
    this.onSendSounds,
  });

  final Function(
    BuildContext context,
    SoundsMessageStatus status,
  )? builder;

  final Function(SoundsMessageStatus status)? onChanged;

  final Function(SendContentType type, String content, int time)? onSendSounds;

  final RecordingMaskOverlayData maskData;

  @override
  State<SoundsMessageButton> createState() => _SoundsMessageButtonState();
}

class _SoundsMessageButtonState extends State<SoundsMessageButton> {
  final scSize = Size(Get.width, Get.height);

  OverlayEntry? _entry;

  final _soundsRecorder = SoundsRecorderController();

  @override
  void initState() {
    super.initState();
    _soundsRecorder.status.addListener(() {
      widget.onChanged?.call(_soundsRecorder.status.value);
    });

    _listener = AppLifecycleListener(
      onStateChange: _onStateChanged,
    );
  }

  @override
  void dispose() {
    _soundsRecorder.reset();
    _listener.dispose();
    super.dispose();
  }

  late final AppLifecycleListener _listener;

  void _onStateChanged(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.detached:
        _onDetached();
      case AppLifecycleState.resumed:
        _onResumed();
      case AppLifecycleState.inactive:
        _onInactive();
      case AppLifecycleState.hidden:
        _onHidden();
      case AppLifecycleState.paused:
        _onPaused();
    }
  }

  void _onDetached() => {};
  void _onResumed() => {};
  void _onInactive() {
    if (_soundsRecorder.status.value == SoundsMessageStatus.recording) {
      _soundsRecorder.endRec();
    }
  }

  void _onHidden() => {};
  void _onPaused() => {};

  _removeMask() {
    if (_entry != null) {
      _entry!.remove();
      _entry = null;
      _soundsRecorder.updateStatus(SoundsMessageStatus.none);
    }
  }

  _showRecordingMask() {
    _entry = OverlayEntry(
      builder: (context) {
        return RepaintBoundary(
          child: RecordingStatusMaskView(
            PolymerData(_soundsRecorder, widget.maskData),
            onCancelSend: () {
              _removeMask();
            },
            onVoiceSend: () {
              widget.onSendSounds?.call(
                  SendContentType.voice,
                  _soundsRecorder.path.value ?? '',
                  _soundsRecorder.duration.value);
              _removeMask();
            },
            onTextSend: () {
              // widget.onSendSounds?.call(SendContentType.text,
              //     _soundsRecorder.textProcessedController.text);
              // _removeMask();
            },
          ),
        );
      },
    );
    Overlay.of(context).insert(_entry!);
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onLongPress: () async {
        PermissionStatus status = await Permission.microphone.status;
        if (status.isGranted) {
          if (!await _soundsRecorder.isEncoderSupported()) {
            return;
          }
          _showRecordingMask();
          _soundsRecorder.beginRec(
            onStateChanged: (state) {
              debugPrint('________  onStateChanged: $state ');
            },
            onAmplitudeChanged: (amplitude) {
              debugPrint(
                  '________  onAmplitudeChanged: ${amplitude.current} , ${amplitude.max} ');
            },
            onDurationChanged: (time) {
              debugPrint('________  onDurationChanged: $time ');
            },
            onCompleted: (path, time) {
              debugPrint('________  onCompleted: $path , $time ');
              if (time < 1) {
                _removeMask();
                EasyLoading.showToast(
                    "The recording time cannot be less than 1s");
                return;
              }

              if (_soundsRecorder.status.value ==
                  SoundsMessageStatus.recording) {
                widget.onSendSounds?.call(SendContentType.voice, path!, time);
                _removeMask();
              } else if (_soundsRecorder.status.value ==
                  SoundsMessageStatus.canceling) {
                _removeMask();
              } else if (_soundsRecorder.status.value ==
                  SoundsMessageStatus.textProcessing) {
                _soundsRecorder.updateStatus(SoundsMessageStatus.textProcessed);
              }
            },
          );
        } else if (status.isDenied) {
          await Permission.microphone.request();
        } else if (status.isPermanentlyDenied) {
          EasyLoading.showToast("You have not authorised this permission.");
        } else {
          EasyLoading.showToast("You have not authorised this permission.");
        }
      },
      onLongPressMoveUpdate: (details) {
        if (_soundsRecorder.status.value == SoundsMessageStatus.none) {
          return;
        }
        final offset = details.globalPosition;
        if ((scSize.height - offset.dy.abs()) >
            widget.maskData.sendAreaHeight) {
          _soundsRecorder.updateStatus(SoundsMessageStatus.canceling);
        } else {
          _soundsRecorder.updateStatus(SoundsMessageStatus.recording);
        }
      },
      onLongPressEnd: (details) async {
        _soundsRecorder.endRec();
      },
      child: ValueListenableBuilder(
        valueListenable: _soundsRecorder.status,
        builder: (context, value, child) {
          if (widget.builder != null) {
            return widget.builder?.call(context, value);
          }
          // ElevatedButton(
          //   style: ElevatedButton.styleFrom(
          //     backgroundColor: Color(0xFF53BFD7),
          //     shape: RoundedRectangleBorder(
          //       borderRadius:
          //           BorderRadius.circular(8),
          //     ),
          //   ),
          //   onPressed: () {},
          //   child: const Padding(
          //     padding: EdgeInsets.symmetric(
          //         horizontal: 12),
          //     child: Text(
          //       'Hold and speak',
          //       style: TextStyle(
          //           color: Colors.white,
          //           fontSize: 14,
          //           fontWeight: FontWeight.bold),
          //     ),
          //   ),
          // ),
          // return Text("111");
          return Container(
            // margin: const EdgeInsets.symmetric(horizontal: 16),
            // width: double.infinity,
            height: 36,
            alignment: Alignment.center,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(8),
              color: Color(0xFF53BFD7),
            ),
            child: Text(
              value.title,
              style: TextStyle(
                  color: Colors.white,
                  fontSize: 14,
                  fontWeight: FontWeight.bold),
            ),
          );
        },
      ),
    );
  }
}
